package com.example.projectmanagement.controller.study;

import com.example.projectmanagement.model.User;
import com.example.projectmanagement.model.study.Video;
import com.example.projectmanagement.service.UserService;
import com.example.projectmanagement.service.study.VideoService;
import com.example.projectmanagement.util.FileSecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/study/videos")
@CrossOrigin
public class VideoUploadController {

    @Autowired
    private VideoService videoService;


    @Autowired
    private UserService userService;

    @Value("${upload.path:uploads/}")
    private String uploadPath;

    /**
     * 上传视频文件
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> uploadVideo(@RequestParam("file") MultipartFile file,
                                                           @RequestParam("title") String title,
                                                           @RequestParam("description") String description,
                                                           @RequestParam("courseId") Long courseId) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 验证文件
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 验证文件扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.lastIndexOf(".") != -1) {
                extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            }

            if (!isValidVideoExtension(extension)) {
                response.put("success", false);
                response.put("message", "只允许上传视频文件（mp4, avi, mov, wmv）");
                return ResponseEntity.badRequest().body(response);
            }

            // 验证文件大小（1GB）
            if (file.getSize() > 1024 * 1024 * 1024) {
                response.put("success", false);
                response.put("message", "视频文件大小不能超过1GB");
                return ResponseEntity.badRequest().body(response);
            }

            // 获取当前用户ID
            Long currentUserId = getCurrentUserId();
            if (currentUserId == null) {
                response.put("success", false);
                response.put("message", "用户未认证");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            // 生成安全的文件名
            String safeFileName = UUID.randomUUID().toString() + extension;

            // 创建上传目录结构 using the standard upload path
            String courseDirPath = uploadPath + "videos/course_" + courseId + "/";
            String absoluteUploadPath = System.getProperty("user.dir") + "/" + courseDirPath;
            Path uploadDir = Paths.get(absoluteUploadPath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 构建文件保存路径
            Path filePath = uploadDir.resolve(safeFileName);

            // 保存文件
            file.transferTo(filePath.toFile());

            // 创建视频实体
            Video video = new Video();
            video.setTitle(title);
            video.setDescription(description);
            video.setFileName(safeFileName);
            video.setFilePath(filePath.toString());
            video.setFileSize(file.getSize());
            video.setCourseId(courseId);
            video.setUrl("/api/study/videos/download/" + courseId + "/" + safeFileName);
            video.setStatus("PENDING"); // 默认设置为待审核状态
            video.setCreatedBy(currentUserId);

            // 保存到数据库
            Video savedVideo = videoService.save(video);

            // 返回成功响应
            response.put("success", true);
            response.put("message", "视频上传成功，等待审核");
            response.put("video", savedVideo);

            return ResponseEntity.ok(response);

        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "视频上传失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "视频上传异常: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 管理员审核视频
     */
    @PutMapping("/{videoId}/approve")
    public ResponseEntity<Map<String, Object>> approveVideo(@PathVariable Long videoId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 获取当前用户ID
            Long currentUserId = getCurrentUserId();
            if (currentUserId == null) {
                response.put("success", false);
                response.put("message", "用户未认证");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            // 检查是否为管理员
            if (!hasRole("ADMIN")) {
                response.put("success", false);
                response.put("message", "没有权限执行此操作");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            // 获取视频
            Video video = videoService.findById(videoId);
            if (video == null) {
                response.put("success", false);
                response.put("message", "视频不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            // 更新视频状态
            video.setStatus("APPROVED");
            video.setApprovedBy(currentUserId);
            video.setApprovedTime(LocalDateTime.now());
            
            Video updatedVideo = videoService.save(video);
            
            response.put("success", true);
            response.put("message", "视频审核通过");
            response.put("video", updatedVideo);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "审核失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 管理员拒绝视频
     */
    @PutMapping("/{videoId}/reject")
    public ResponseEntity<Map<String, Object>> rejectVideo(@PathVariable Long videoId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 获取当前用户ID
            Long currentUserId = getCurrentUserId();
            if (currentUserId == null) {
                response.put("success", false);
                response.put("message", "用户未认证");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            // 检查是否为管理员
            if (!hasRole("ADMIN")) {
                response.put("success", false);
                response.put("message", "没有权限执行此操作");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            // 获取视频
            Video video = videoService.findById(videoId);
            if (video == null) {
                response.put("success", false);
                response.put("message", "视频不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            // 更新视频状态
            video.setStatus("REJECTED");
            video.setApprovedBy(currentUserId);
            video.setApprovedTime(LocalDateTime.now());
            
            Video updatedVideo = videoService.save(video);
            
            response.put("success", true);
            response.put("message", "视频审核拒绝");
            response.put("video", updatedVideo);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "拒绝失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 获取所有已批准的视频（公开可见）
     */
    @GetMapping("/approved")
    public ResponseEntity<Map<String, Object>> getApprovedVideos() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<Video> videos = videoService.findByStatus("APPROVED");
            response.put("success", true);
            response.put("videos", videos);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取已批准视频失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 获取所有视频（仅管理员可见）
     */
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> getAllVideos() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查是否为管理员
            if (!hasRole("ADMIN")) {
                response.put("success", false);
                response.put("message", "没有权限执行此操作");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            Iterable<Video> videos = videoService.findAll();
            List<Video> videoList = new ArrayList<>();
            videos.forEach(videoList::add);
            
            response.put("success", true);
            response.put("videos", videoList);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取所有视频失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 获取指定课程的所有视频（仅显示已批准的视频）
     */
    @GetMapping("/course/{courseId}")
    public ResponseEntity<Map<String, Object>> getCourseVideos(@PathVariable Long courseId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<Video> videos = videoService.findByCourseIdAndStatus(courseId, "APPROVED");
            response.put("success", true);
            response.put("videos", videos);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取视频失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 获取指定用户上传的所有视频
     */
    @GetMapping("/created-by/{userId}")
    public ResponseEntity<Map<String, Object>> getUserVideos(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // For security, we should verify the user is either admin or the owner
            Long currentUserId = getCurrentUserId();
            if (currentUserId == null) {
                response.put("success", false);
                response.put("message", "用户未认证");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            // Check if user is admin or the owner of videos
            if (!hasRole("ADMIN") && !currentUserId.equals(userId)) {
                response.put("success", false);
                response.put("message", "没有权限执行此操作");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            // For simplicity in this demo, we're just getting all videos for now
            // In a real implementation, we'd want to filter by user ID
            List<Video> videos = videoService.findAllByUserId(userId);
            response.put("success", true);
            response.put("videos", videos);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取视频失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 删除视频（上传者或管理员可删除）
     */
    @DeleteMapping("/{videoId}")
    public ResponseEntity<Map<String, Object>> deleteVideo(@PathVariable Long videoId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 获取当前用户ID
            Long currentUserId = getCurrentUserId();
            if (currentUserId == null) {
                response.put("success", false);
                response.put("message", "用户未认证");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            // 获取视频
            Video video = videoService.findById(videoId);
            if (video == null) {
                response.put("success", false);
                response.put("message", "视频不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            // 检查权限：上传者或管理员可以删除
            if (!video.getCreatedBy().equals(currentUserId) && !hasRole("ADMIN")) {
                response.put("success", false);
                response.put("message", "没有权限删除此视频");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            // 删除文件
            Path filePath = Paths.get(video.getFilePath());
            if (Files.exists(filePath)) {
                Files.delete(filePath);
            }

            // 删除数据库记录
            videoService.deleteById(videoId);
            
            response.put("success", true);
            response.put("message", "视频删除成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 下载视频文件
     */
    @GetMapping("/download/{courseId}/{fileName}")
    public ResponseEntity<byte[]> downloadVideo(@PathVariable Long courseId, @PathVariable String fileName, Authentication authentication) {
        try {
            // 验证文件名安全性
            if (fileName == null || fileName.isEmpty() || fileName.contains("..")) {
                return ResponseEntity.badRequest().build();
            }

            // 构造文件路径 - 使用课程特定目录
            String courseDirPath = uploadPath + "videos/course_" + courseId + "/";
            String absoluteUploadPath = System.getProperty("user.dir") + "/" + courseDirPath;
            Path filePath = Paths.get(absoluteUploadPath, fileName);
            
            // 安全检查：确保文件在允许的目录中
            Path normalizedPath = filePath.normalize();
            Path projectDirPath = Paths.get(System.getProperty("user.dir")).toAbsolutePath().normalize();
            
            // 确保路径在项目目录内
            if (!normalizedPath.startsWith(projectDirPath)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
            
            if (!Files.exists(filePath)) {
                return ResponseEntity.notFound().build();
            }
            
            // 检查用户是否有权限访问该视频
            // 1. 获取当前用户
            if (authentication == null || !authentication.isAuthenticated()) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            
            // 2. 获取视频信息
            String username = authentication.getName();
            // In a real implementation, you would check if the user has access to this video
            // For now, we'll allow access if the user is authenticated
            
            byte[] fileBytes = Files.readAllBytes(filePath);
            return ResponseEntity.ok()
                    .header("Content-Disposition", "inline; filename=\"" + fileName + "\"")
                    .body(fileBytes);
                    
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取待审核的视频列表（仅管理员可见）
     */
    @GetMapping("/pending")
    public ResponseEntity<Map<String, Object>> getPendingVideos() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查是否为管理员
            if (!hasRole("ADMIN")) {
                response.put("success", false);
                response.put("message", "没有权限执行此操作");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            List<Video> videos = videoService.findByStatus("PENDING");
            response.put("success", true);
            response.put("videos", videos);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取待审核视频失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 获取当前认证用户的ID
     */

    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String username = userDetails.getUsername();
            // 根据用户名获取用户ID
            return userService.getUserByUsername(username).map(User::getId).orElse(null);
        }
        return null;
    }

    /**
     * 检查用户是否具有指定角色
     */
    private boolean hasRole(String roleName) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            return authentication.getAuthorities().stream()
                    .anyMatch(authority -> authority.getAuthority().equals("ROLE_" + roleName));
        }
        return false;
    }

    /**
     * 验证是否为允许的视频扩展名
     */
    private boolean isValidVideoExtension(String extension) {
        if (extension == null) return false;
        return ".mp4".equals(extension) || ".avi".equals(extension) || ".mov".equals(extension) || ".wmv".equals(extension);
    }
}